import {App, ViewController} from "ionic-angular";
import {Component, ElementRef} from "@angular/core";
import {PublicService} from "../../common/public.service";
import {DatePicker} from "@ionic-native/date-picker";
import {HttpService} from "../../providers/HttpService";
import {PROCEDURE_URL, SET_GROUP_RESULT_URL, SET_GROUP_URL, STATION_LIST_URL} from "../../providers/Constants";

@Component({
  selector: 'page-set-work',
  templateUrl: 'set-work.html',
})

/**
 * 1、每次登陆弹出页面
 * 2、点击确定关闭页面
 * 3、如果未设置班组，点击确定提交班组设置
 * 4、如果该班组设置过（未修改数据），则不提交到服务器
 * 5、如果班组已设置，且未开始扫码考勤则可修改班组数据
 * 6、如果班组已设置，且已开始扫码考勤则不可更改班组数据（服务器判断是否能够更改）
 *
 */
export class SetWorkPage {

  bzDate: string;//班组日期
  minDate: string;//最小日期
  bzSelect: string = "A";//班组选择

  workInTime: string;//上班时间
  workOutTime: string;//下班时间
  workProcedure: string = sessionStorage.getItem("workProcedure");//工序

  public workProcedures: Array<Object> = JSON.parse(localStorage.getItem("mpower-workProcedure"));

  constructor(public pub: PublicService,
              public datePicker: DatePicker,
              public viewCtrl: ViewController,
              public element: ElementRef,
              public app: App,
              public http: HttpService) {
  }

  ionViewDidLoad() {
    this.getWorkProcedure();
    this.bzDate = sessionStorage.getItem("fdNowDate").substr(0, 10);
    if (!this.workProcedure && this.workProcedures) {
      this.workProcedure = this.workProcedures[0]['code'];
    }
    this.initTeam(this.workProcedure);
  }

  /**
   * 初始化班组数据
   * 根据工序初始化班组、班组日期
   */
  initTeam(wpcode: string) {
    if (this.workProcedures && this.workProcedures.length > 0) {
      for (let i = 0; i < this.workProcedures.length; i++) {
        if (wpcode == this.workProcedures[i]['code']) {
          let activeGroup = this.workProcedures[i]['activeGroup'];
          this.element.nativeElement.querySelector("#radioA").style.display = "none";
          this.element.nativeElement.querySelector("#spanA").style.display = "none";
          this.element.nativeElement.querySelector("#radioB").style.display = "none";
          this.element.nativeElement.querySelector("#spanB").style.display = "none";
          if (activeGroup.length == 1) {
            this.element.nativeElement.querySelector("#radio" + activeGroup[0]).style.display = "";
            this.element.nativeElement.querySelector("#span" + activeGroup[0]).style.display = "";
            this.bzSelect = activeGroup[0];
          } else {
            this.bzSelect = sessionStorage.getItem("setBzSelect") ? sessionStorage.getItem("setBzSelect") : activeGroup[0];
            this.element.nativeElement.querySelector("#radioA").style.display = "";
            this.element.nativeElement.querySelector("#spanA").style.display = "";
            this.element.nativeElement.querySelector("#radioB").style.display = "";
            this.element.nativeElement.querySelector("#spanB").style.display = "";
          }
        }
      }
    }
    if (this.bzDate && this.bzSelect && wpcode) {
      this.getGroupResult(this.bzDate, this.bzSelect, wpcode);
    }
  }


  /**
   * 设置班组日期
   * 可选最近三天（今天前后各一天）
   */
  getDate() {
    this.datePicker.show({
      titleText: "",
      date: this.bzDate,
      mode: 'date',
      minDate: this.pub.getDate(new Date(this.bzDate), -1),
      maxDate: this.pub.getDate(new Date(this.bzDate), 1),
      is24Hour: true,
      androidTheme: this.datePicker.ANDROID_THEMES.THEME_HOLO_LIGHT
    }).then(
      date => {//如果时间变化则重新调用班组时间信息
        if (this.bzDate != this.pub.getDate(date, 0)) {
          if (this.pub.getDate(date, 0)) {
            this.getGroupResult(this.pub.getDate(date, 0), this.bzSelect, this.workProcedure);
          }
          this.bzDate = this.pub.getDate(date, 0);
        }
      },
      err => {
        console.log('Error occurred while getting date: ', err);
      }
    );
  }

  /**
   * 上班时间
   */
  getWorkTnTime() {
    this.datePicker.show({
      titleText: "",
      date: new Date(),
      mode: 'datetime',
      is24Hour: true,
      androidTheme: this.datePicker.ANDROID_THEMES.THEME_HOLO_LIGHT
    }).then(
      date => {
        this.workInTime = this.pub.getYMDHM(date, 0);
        this.workOutTime = this.pub.getYMDHM(date, 12 * 60 * 60 * 1000);
      },
      err => {
        console.log('Error occurred while getting date: ', err);
      }
    );
  }

  /**
   * 下班时间
   */
  getWorkOutTime() {
    if (!this.workInTime) {
      return;
    }
    this.datePicker.show({
      titleText: "",
      date: this.pub.stringToDate(this.workOutTime),
      mode: 'datetime',
      minDate: this.workInTime,
      is24Hour: true,
      androidTheme: this.datePicker.ANDROID_THEMES.THEME_HOLO_LIGHT
    }).then(
      date => {
        this.workOutTime = this.pub.getYMDHM(date, 0);
      },
      err => {
        console.log('Error occurred while getting date: ', err);
      }
    );
  }

  /**
   * 保存设置
   * 1、如果未设置班组，点击确定提交班组设置
   * 2、如果该班组设置过（未修改数据），则不提交到服务器
   * 3、如果班组已设置，且未开始扫码考勤则可修改班组数据
   * 4、如果班组已设置，且已开始扫码考勤则不可更改班组数据（服务器判断是否能够更改）
   */
  submitBtn() {
    if (!this.workProcedure || this.workProcedure == 'null' || this.workProcedure == 'undefined') {
      this.pub.presentLoadingToast("请选择工序");
      return;
    }
    if (!this.bzDate) {
      this.pub.presentLoadingToast("请设置班组日期");
      return;
    }
    if (!this.workInTime) {
      this.pub.presentLoadingToast("请设置上班时间");
      return;
    }
    if (!this.workOutTime) {
      this.pub.presentLoadingToast("请设置下班时间");
      return;
    }

    //判断下班时间不能小于上班时间
    let workOutTime_M = this.pub.stringToDate(this.workOutTime).getTime();
    let workInTime_M = this.pub.stringToDate(this.workInTime).getTime();

    if (!(workOutTime_M > workInTime_M)) {
      this.pub.presentLoadingToast("下班时间必须大于上班时间");
      return;
    }

    //判断班组数据是否更改，如果未更改则不提交服务器
    /*if (localStorage.getItem("groupId")) {
      if (sessionStorage.getItem("setWorkTime") == this.bzDate
        && sessionStorage.getItem("setBzSelect") == this.bzSelect
        && sessionStorage.getItem("workProcedure") == this.workProcedure
        && sessionStorage.getItem("setWorkInTime") == this.workInTime
        && sessionStorage.getItem("setWorkOutTime") == this.workOutTime) {
        this.pub.presentLoadingToast("设置成功");
        setTimeout(() => {
          this.viewCtrl.dismiss();
        }, 1000);
        return;
      }
    }*/

    this.pub.presentCustomConfirm("确定设置吗？", "取消", "确定").then(() => {
      let params = {
        sessionId: sessionStorage.getItem("session"),
        fdDate: this.bzDate,
        fdType: this.bzSelect,
        fdProcedure: this.workProcedure,
        fdStartTime: this.workInTime,
        fdEndTime: this.workOutTime
      };
      this.http.get(SERVER_URL + SET_GROUP_URL, '&', params, true).then(res => {
        if (res.success) {

          sessionStorage.setItem("fdNowDate",this.bzDate);
          sessionStorage.setItem("setWorkTime", res.groupSetInfo.fdDate);
          sessionStorage.setItem("setWorkInTime", res.groupSetInfo.fdStartTime);
          sessionStorage.setItem("setWorkOutTime", res.groupSetInfo.fdEndTime);
          sessionStorage.setItem("setBzSelect", res.groupSetInfo.fdType);
          sessionStorage.setItem("workProcedure", res.groupSetInfo.fdProcedure);
          sessionStorage.setItem("workProcedureName", res.groupSetInfo.fdProcedureName);

          sessionStorage.setItem("fdDeptId", res.groupSetInfo.fdDeptId);
          sessionStorage.setItem("fdDeptName", res.groupSetInfo.fdDeptName);
          sessionStorage.setItem("fdIsLock", res.groupSetInfo.fdIsLock);//是否锁定
          sessionStorage.setItem("fdIsShift", res.groupSetInfo.fdIsShift);//是否交班
          localStorage.setItem("groupId", res.groupId);

          this.pub.presentLoadingToast(res.msg);
          this.getHandleTypes();
        } else {
          this.pub.presentLoadingToast(res.msg);
          if (res.timeout) {
            setTimeout(() => {
              this.app.getRootNav().setRoot('LoginPage');
            }, 1500);
          }
        }
      });
      setTimeout(() => {
        this.viewCtrl.dismiss();
      }, 2000);
    }).catch(() => {
      setTimeout(() => {
        this.viewCtrl.dismiss();
      }, 2000);
    })
  }

  /**
   * 工序
   */
  getWorkProcedure() {
    let params = {sessionId: sessionStorage.getItem("session")};
    this.http.get(SERVER_URL + PROCEDURE_URL, '&', params, false).then(res => {
      if (res.success) {
        this.workProcedures = res.data.procedures;
        localStorage.setItem("mpower-workProcedure", JSON.stringify(res.data.procedures));
      } else {
        this.pub.presentLoadingToast(res.msg);
        if (res.timeout) {
          setTimeout(() => {
            this.app.getRootNav().setRoot('LoginPage');
          }, 1500);
        }
      }
    });
  }

  /**
   * 工站类型
   */
  getHandleTypes() {
    let params = {sessionId: sessionStorage.getItem("session"), groupId: localStorage.getItem("groupId")};
    this.http.get(SERVER_URL + STATION_LIST_URL, '&', params, false).then(res => {
      if (res.success) {
        localStorage.setItem("mpower-handleTypes", JSON.stringify(res.data.stations));
      } else {
        this.pub.presentLoadingToast(res.msg);
        if (res.timeout) {
          setTimeout(() => {
            this.app.getRootNav().setRoot('LoginPage');
          }, 1500);
        }
      }
    });
  }

  /**
   * 获取当前用户已设置班组数据
   * @param bzDate 班组日期
   * @param bzSelect 班组
   * @param workProcedure 工序
   */
  getGroupResult(bzDate: string, bzSelect: string, workProcedure: string) {
    let params = {
      sessionId: sessionStorage.getItem("session"),
      fdDate: bzDate,
      fdType: bzSelect,
      fdProcedure: workProcedure
    };
    this.http.get(SERVER_URL + SET_GROUP_RESULT_URL, '&', params, true).then(res => {
      if (res.success) {
        if (res.data.id) {//已设置过
          this.workInTime = res.data.fdStartTime;
          this.workOutTime = res.data.fdEndTime;
          sessionStorage.setItem("setWorkInTime", res.data.fdStartTime);
          sessionStorage.setItem("setWorkOutTime", res.data.fdEndTime);
        } else {//未设置则默认当前时间
          this.workInTime = this.bzDate + " " + this.pub.getCurrentHM(new Date(), 0);
          this.workOutTime = this.bzDate + " " + this.pub.getCurrentHM(new Date(), 12 * 60 * 60 * 1000);
        }
      } else {
        this.pub.presentLoadingToast(res.msg);
        if (res.timeout) {
          setTimeout(() => {
            this.app.getRootNav().setRoot('LoginPage');
          }, 1500);
        }
      }
    });
  }

  /**
   * 更改班组重新获取服务器已设置班组时间
   */
  changeBzSelect() {
    if (this.bzDate && this.bzSelect && this.workProcedure) {
      this.getGroupResult(this.bzDate, this.bzSelect, this.workProcedure);
    }
  }
}
